package com.gitee.huanminabc.fastboot.web.servlet;

import com.gitee.huanminabc.fastboot.web.config.AppServletConfig;
import com.gitee.huanminabc.fastboot.context.AppContext;
import com.gitee.huanminabc.fastboot.web.context.AppWebContext;
import com.gitee.huanminabc.jnetty.server.NettyServer;
import com.gitee.huanminabc.jnetty.server.handler.HttpClientMessageHandler;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 简要描述
 *
 * @Author: huanmin
 * @Date: 2025/4/6 21:22
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
@Slf4j
public class NettyServe {
    private static final Object lock = new Object();
    public static NettyServer nettyServer;

    public static void start() {
        //启动netty服务
        Thread thread = new Thread(() -> {
            //启动web服务
            AppServletConfig appServletConfig = AppWebContext.appServletConfig;
            nettyServer = new NettyServer(appServletConfig.getPort(), (p) -> {
                // http 消息解码器
                p.addLast(new HttpServerCodec());
                // 对大数据流的支持
                p.addLast(new ChunkedWriteHandler());
                // http 消息合并
                p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                // http 消息压缩
                p.addLast(new HttpContentCompressor());
                //逻辑处理
                p.addLast(new HttpClientMessageHandler(new HttpInterfaceHandlerImpl(), appServletConfig.getMaxConnections()));
            });
            //在dev环境下开启内存泄漏检测
            if (AppContext.profiles.contains("dev")) {
                nettyServer.setOpenMemoryLeakDetection(true);
            }
            nettyServer.setAppRunFutureConsumer((future) -> {
                if (!future.isSuccess()) {
                    //启动失败
                    log.error("netty server run error: ", future.cause());
                    System.exit(1);
                }
            });
            try {
                nettyServer.startSync();
            } catch (Exception e) {
                log.error("netty server start error: ", e);
                 System.exit(1);
            }
        });
        //非守护线程,让主线程等着不要退出
        thread.start();
    }

    public static void shutdown() {
        if (nettyServer != null) {
            nettyServer.close();
            synchronized (lock) {
                lock.notify();
            }
        }
    }

}
